using System;
using Microsoft.Xna.Framework;

namespace TileEngine
{
    public class FpsCounter : GameComponent
    {
        float updateInterval = 1.0f;
        float timeSinceLastUpdate = 0.0f;
        float frameCount = 0;

        float fps = 0;

        public float FPS
        {
            get { return this.fps; }
        }

        public FpsCounter(Game game)
            : base(game) { }

        public event EventHandler<EventArgs> Updated;

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            float elapsed = (float)gameTime.ElapsedRealTime.TotalSeconds;

            this.frameCount++;
            this.timeSinceLastUpdate += elapsed;

            if (this.timeSinceLastUpdate > this.updateInterval)
            {
                fps = this.frameCount / this.timeSinceLastUpdate;
                this.frameCount = 0;
                this.timeSinceLastUpdate -= this.updateInterval;

                if (Updated != null)
                {
                    Updated(this, new EventArgs());
                }
            }
        }
    }
}
